export const vSwipe = {
  mounted(el, binding) {
    const config = {
      minDistance: 30,
      allowVerticalScroll: true,  // 新增：允许垂直滚动
      ...binding.value
    };

    let startX = 0;
    let startY = 0;
    let isSwiping = false;

    // 触摸开始（不阻止默认行为）
    const handleTouchStart = (e) => {
      if (e.touches.length !== 1) return;
      const touch = e.touches[0];
      startX = touch.clientX;
      startY = touch.clientY;
      isSwiping = false;
    };

    // 触摸移动（动态判断是否需要阻止滚动）
    const handleTouchMove = (e) => {
      if (!isSwiping && config.allowVerticalScroll) return;
      
      const touch = e.touches[0];
      const deltaX = touch.clientX - startX;
      const deltaY = touch.clientY - startY;

      // 当检测到明显横向滑动时，才阻止滚动
      if (Math.abs(deltaX) > Math.abs(deltaY)) {
        e.preventDefault();
        isSwiping = true;
      }
    };

    // 触摸结束（精准触发）
    const handleTouchEnd = (e) => {
      const touch = e.changedTouches[0];
      const deltaX = touch.clientX - startX;
      const deltaY = touch.clientY - startY;

      if (
        !isSwiping &&  // 关键：只有未标记为滑动时才允许其他事件
        Math.abs(deltaX) > config.minDistance &&
        Math.abs(deltaX) > Math.abs(deltaY)
      ) {
        binding.value?.({ 
          direction: deltaX > 0 ? 'right' : 'left',
          deltaX,
          originEvent: e 
        });
      }

      isSwiping = false;
    };

    // 绑定事件（使用 passive 提升滚动性能）
    el.addEventListener('touchstart', handleTouchStart, { passive: true });
    el.addEventListener('touchmove', handleTouchMove, { passive: !config.allowVerticalScroll });
    el.addEventListener('touchend', handleTouchEnd);

    // 保存引用
    el._swipeHandlers = { handleTouchStart, handleTouchMove, handleTouchEnd };
  },

  unmounted(el) {
    if (el._swipeHandlers) {
      const { handleTouchStart, handleTouchMove, handleTouchEnd } = el._swipeHandlers;
      el.removeEventListener('touchstart', handleTouchStart);
      el.removeEventListener('touchmove', handleTouchMove);
      el.removeEventListener('touchend', handleTouchEnd);
      delete el._swipeHandlers;
    }
  }
};
